package com.zxx.coolweather._wuguan2;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadQueue;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.yanzhenjie.nohttp.download.SimpleDownloadListener;
import com.yanzhenjie.nohttp.download.SyncDownloadExecutor;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.error.ServerError;
import com.yanzhenjie.nohttp.error.StorageReadWriteError;
import com.yanzhenjie.nohttp.error.StorageSpaceNotEnoughError;
import com.yanzhenjie.nohttp.error.TimeoutError;
import com.yanzhenjie.nohttp.error.URLError;
import com.yanzhenjie.nohttp.error.UnKnownHostError;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.nohttp.rest.StringRequest;
import com.zxx.coolweather.R;
import com.zxx.coolweather._wuguan2.async.MultiAsynctaskNetwork;
import com.zxx.coolweather._wuguan2.async.NetworkInterface;

import java.net.HttpCookie;
import java.util.List;

public class NoHttpActivity extends AppCompatActivity implements View.OnClickListener {

    private final int NOHTTP_LOGIN = 0x01;//登陆
    private final int NOHTTP_LOGOUT = 0x02;//退出

    private TextView tvResult;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_no_http);

        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.btn_logout).setOnClickListener(this);
        tvResult = findViewById(R.id.tv_result);
        imageView = findViewById(R.id.image);

        setDownView();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_login) {
            String url = "http://guolin.tech/api/weather";
            //1.返回json数据
            //            RequestFastJson request = new RequestFastJson(url);

            //2.返回bean类
            RequestWeatherBean request = new RequestWeatherBean(url, RequestMethod.GET);

            //JsonObjectRequest request1 = new JsonObjectRequest(Constants.LOGIN);
            request.add("cityid", "CN101210106");
            request.add("key", "bc0418b57b2d4918819d3974ac1285d9");

            CallServer.getInstance().add(this, request, callBack2, NOHTTP_LOGIN, true, false, true);

        } else {
            //String url = "http://guolin.tech/api/weather?cityid=CN101210106&key=bc0418b57b2d4918819d3974ac1285d9";
            //JsonObjectRequest request = new JsonObjectRequest(Constants.LOGIN);
            //RequestFastJson request = new RequestFastJson(url);

            //缓存
            //request.setCacheMode(CacheMode.DEFAULT);// 表示走Http标准协议，默认就是，这里可以不用设置
            //request.setCacheMode(CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE);// 表示走请求失败的时候读取缓存
            //request.setCacheMode(CacheMode.NONE_CACHE_REQUEST_NETWORK);// 表示没有缓存的时候去请求服务器
            //request.setCacheMode(CacheMode.ONLY_READ_CACHE);// ONLY_READ_CACHE表示仅仅请求缓存，不请求服务器
            //CallServer.getInstance().add(this, request, callBack, NOHTTP_LOGOUT, true, false, true);

            // 如果没有缓存才去请求服务器，否则使用缓存，缓存图片演示，这一点非常适合封装一个自己的Imageloader是来使用
            String imageUrl = "https://img-blog.csdnimg.cn/img_convert/c988cb88d0fb3d2e97bafc0393f9780a.png";
            Request<Bitmap> imageRequest = NoHttp.createImageRequest(imageUrl);
            imageRequest.setCacheMode(CacheMode.NONE_CACHE_REQUEST_NETWORK);
            CallServer.getInstance().add(this, imageRequest, callBack3, NOHTTP_LOGOUT, true, false, true);
        }
    }

    //返回json
    private HttpCallBack<JSONObject> callBack = new HttpCallBack<JSONObject>() {
        @Override
        public void onSucceed(int what, Response<JSONObject> response) {
            JSONObject jsonObject = response.get();

            String myCookie = null;
            //如果有cookie
            Headers headers = response.getHeaders();
            List<HttpCookie> cookies = headers.getCookies();
            for (HttpCookie cookie : cookies) {
                String cookieName = cookie.getName();
                if ("userInfo".equals(cookieName)) {
                    // 这里就拿到了你想那的cookie
                    myCookie += cookie.getValue();
                    myCookie += "\n";
                }
            }
            //cookie介绍
            //https://blog.csdn.net/sinat_31057219/article/details/74217030


            if (what == NOHTTP_LOGIN) {
                tvResult.setText("登录接口：" + jsonObject.getString("HeWeather"));
            } else if (what == NOHTTP_LOGOUT) {
                tvResult.setText("退出接口数据：" + jsonObject.getString("HeWeather"));
            }
        }

        @Override
        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
            tvResult.setText("请求失败");
        }
    };

    //返回bean
    private HttpCallBack<WeatherBean> callBack2 = new HttpCallBack<WeatherBean>() {
        @Override
        public void onSucceed(int what, Response<WeatherBean> response) {
            WeatherBean bean = response.get();
            if (what == NOHTTP_LOGIN) {
                tvResult.setText("登录接口：" + bean.HeWeather.get(0).toString());
            } else if (what == NOHTTP_LOGOUT) {
                tvResult.setText("退出接口数据：" + bean.HeWeather.get(0).update.toString());
            }
        }

        @Override
        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
            tvResult.setText("请求失败");
        }
    };

    //返回bean
    private HttpCallBack<Bitmap> callBack3 = new HttpCallBack<Bitmap>() {
        @Override
        public void onSucceed(int what, Response<Bitmap> response) {
            imageView.setImageBitmap(response.get());
        }

        @Override
        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
            tvResult.setText("请求失败");
        }
    };

    //-----------------------------------------------------------------
    //---下载
    //-----------------------------------------------------------------
    private TextView mBtnStart;
    private TextView mTvResult;
    private ProgressBar mProgressBar;
    private String url = "https://webhdfstest.eyar.com/tccloud/hbd/test/2021/12/29/cbc19b078c4650c7446e307ed7f4d289?fn=OLMA-Phone_V2.6.0.51640762513608.apk";
    private DownloadRequest downloadRequest;
    private DownloadQueue downloadQueue;

    private int mProgress;

    private void setDownView() {
        mProgressBar = findViewById(R.id.pb_progress);
        mBtnStart = findViewById(R.id.btn_start_download);
        mTvResult = findViewById(R.id.tv_result2);

        //https://github.com/yanzhenjie/NoHttp

        // url 下载地址
        // fileFolder 保存的文件夹
        // fileName 文件名
        // isRange 是否断点续传下载
        // isDeleteOld 如果发现文件已经存在是否删除后重新下载
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        //同步下载-SyncDownloadExecutor
        downloadRequest = new DownloadRequest(url, RequestMethod.GET, path, true, true);

        //异步下载
        downloadQueue = NoHttp.newDownloadQueue();
        //downloadRequest = NoHttp.createDownloadRequest(url, path, "nohttp_优领.apk", true, false);


        // 检查已经下载了一半的文件是什么状态
        int status = downloadRequest.checkBeforeStatus();
        if (status == DownloadRequest.STATUS_FINISH) {
            mTvResult.setText("下载完成");
            mBtnStart.setText("已经下载完成");
            //。。。。提示安装
        } else if (status == DownloadRequest.STATUS_RESTART) {
            // 代表文件不存在，需要从头下载
            mTvResult.setText("");
            mBtnStart.setText("下载");
        } else if (status == DownloadRequest.STATUS_RESUME) {
            // 代表文件已经下载了一半了
            //int progress = AppConfig.getInstance().getInt(PROGRESS_KEY, 0);
            mProgressBar.setProgress(mProgress);
            mTvResult.setText("已经下载了 " + mProgress + "%");
            mBtnStart.setText("继续下载");
        }

        mBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //没用
                //if (downloadRequest.isStarted()) {
                //    downloadRequest.cancel();
                //    //downloadQueue.stop();
                //} else {

                    //同步（报错）
//                    downloadSyncQueue();

                    //异步
                    //downloadAsyQueue();
                //}


                MultiAsynctaskNetwork network = new MultiAsynctaskNetwork(new NetworkInterface() {
                    @Override
                    public void onResult(String result) {
                        Log.e("Tag-->", "结果：" + result);
                    }
                });
                network.execute();
            }
        });
    }

    // 开始或者继续一个下载。
    public void startDownload() {
        if(downloadRequest != null)
            downloadRequest = new DownloadRequest(url, RequestMethod.GET, "/sdcard/", "xx.apk", true, true);
    }

    // 暂停或者取消一个下载。
    public void stopDownload() {
        if(downloadRequest != null)
            downloadRequest.cancel();
    }

    private void downloadSyncQueue() {
        try {
//            SyncDownloadExecutor.INSTANCE.execute(0,downloadRequest,downloadListener);
            SyncDownloadExecutor.AsyncRequestExecutor.execute(0, downloadRequest, downloadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void downloadAsyQueue() {
        downloadQueue.add(0, downloadRequest, downloadListener);

        //downloadQueue.start();
    }

    private final DownloadListener downloadListener = new DownloadListener() {
        /**
         * @param what 代表哪一个下载
         * @param isResume  是不是断点续续传开始下载的
         * @param beforeLenght  断点开始的地方的文件大小
         * @param headers   本地请求的时候的响应头
         * @param allCount  本次需要下载多少
         */
        @Override
        public void onStart(int what, boolean isResume, long beforeLenght, Headers headers, long allCount) {
            //int progress = AppConfig.getInstance().getInt(PROGRESS_KEY, 0);
            mTvResult.setText("已下载: " + mProgress + "%");
            mBtnStart.setText("暂停");
        }

        @Override
        public void onProgress(int what, int progress, long fileCount, long speed) {
            // 进度发生变化，服务器不返回文件总大小时不回调，因为没法计算进度。
            // 参数1：what。
            // 参数2：进度，[0-100]。
            // 参数3：文件总大小，可能为0，因为服务器可能不返回文件大小。
            // 参数4：下载的速度，含义为1S下载的byte大小，计算下载速度时：
            //        int xKB = (int) speed / 1024; // 单位：xKB/S
            //        int xM = (int) speed / 1024 / 1024; // 单位：xM/S

            //super.onProgress(what, progress, fileCount, speed);
            //AppConfig.getInstance().putInt(PROGRESS_KEY, progress);
            Log.e("Tag-->", progress + "<--");

            mProgress = progress;

            mProgressBar.setProgress(progress);
            mTvResult.setText("已经下载了 " + progress + "%");
        }

        @Override
        public void onDownloadError(int what, Exception exception) {
            mBtnStart.setText("再次尝试");

            String message = "下载出错了：";
            if (exception instanceof ServerError) {
                message += "服务器发生内部错误";
            } else if (exception instanceof NetworkError) {
                message += "网络不可用，请检查网络";
            } else if (exception instanceof StorageReadWriteError) {
                message += "存储卡错误，请检查存储卡";
            } else if (exception instanceof StorageSpaceNotEnoughError) {
                message += "存储位置空间不足";
            } else if (exception instanceof TimeoutError) {
                message += "下载超时";
            } else if (exception instanceof UnKnownHostError) {
                message += "服务器找不到";
            } else if (exception instanceof URLError) {
                message += "url地址错误";
            } else {
                message += "未知错误";
            }
            mTvResult.setText(message);
        }

        @Override
        public void onFinish(int what, String filePath) {
            mTvResult.setText("下载完成，文件保存在：" + filePath);
        }

        @Override
        public void onCancel(int what) {
            mTvResult.setText("下载暂停");
            mBtnStart.setText("继续下载");
        }
    };



}